/**
 * 
 */
package com.siriusxm.www.mavencore.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.siriusxm.www.mavencore.domain.User;

/**
 * @author sbaral
 *
 */
public class UserDao implements IUserDao {

//	private final static Map<String, User> userRegistry = new HashMap<String, User>();
	
	private SessionFactory sessionFactory;
	
	/* (non-Javadoc)
	 * @see com.siriusxm.www.mavencore.dao.IUserDao#login(java.lang.String, java.lang.String)
	 */
	@Override
	public User login(String username, String password) {
		Session session = sessionFactory.openSession();
		User user = (User) session.createCriteria(User.class)
				.add(Restrictions.eq("username", username))
				.add(Restrictions.eq("password", password))
				.uniqueResult();
		session.close();
		return user;
	}

	/* (non-Javadoc)
	 * @see com.siriusxm.www.mavencore.dao.IUserDao#register(com.siriusxm.www.mavencore.domain.User)
	 */
	@Override
	public void register(User user) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.save(user);
		transaction.commit();
		session.close();
	}

	/* (non-Javadoc)
	 * @see com.siriusxm.www.mavencore.dao.IUserDao#modify(com.siriusxm.www.mavencore.domain.User)
	 */
	@Override
	public User modify(User user) {
		Session session = sessionFactory.openSession();
		session.update(user);
		return user;
	}

	/* (non-Javadoc)
	 * @see com.siriusxm.www.mavencore.dao.IUserDao#delete(com.siriusxm.www.mavencore.domain.User)
	 */
	@Override
	public void delete(User user) {
		User existingUser = (User) sessionFactory.getCurrentSession().load(
                User.class, user.getId());
        if (null != existingUser) {
            sessionFactory.getCurrentSession().delete(user);
        }
	}

	/* (non-Javadoc)
	 * @see com.siriusxm.www.mavencore.dao.IUserDao#getAllUsers()
	 */
	@Override
	public List<User> getAllUsers() {
		return sessionFactory.getCurrentSession().createQuery("from User").list();
	}
	
	/**
	 * @return the sessionFactory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * @param sessionFactory the sessionFactory to set
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}


}
